package com.exchange.used.config.utils;

import org.springframework.util.ResourceUtils;

import java.io.*;
import java.net.URLDecoder;

public class FileUploadUtil {
    public static String saveFile(InputStream fileSource, String oldFileName) throws IOException {
        String realPath = null;
        try {
            realPath = ResourceUtils.getURL(ResourceUtils.CLASSPATH_URL_PREFIX + "upload/").getPath().substring(1);
            realPath = URLDecoder.decode(realPath, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        File fileupload = new File(realPath);
        if (!fileupload.exists()) {//如服务器上传位置不存在，则创建
            try {
                fileupload.mkdir();
            } catch (Exception e) {
                System.out.println("服务器上传位置创建异常");
                e.printStackTrace();
            }
        }
        String ext = oldFileName.substring(oldFileName.lastIndexOf("."));//取得原文件后缀名
        String newFileName = System.nanoTime() + ext;//为上传后文件命名
        String saveFileRealPath = (realPath + newFileName);
        File newFile = new File(saveFileRealPath);
        BufferedInputStream bis = new BufferedInputStream(fileSource);    //输入流
        FileOutputStream outputStream = new FileOutputStream(newFile);
        BufferedOutputStream bos = new BufferedOutputStream(outputStream);    //输出流
        int n;
        try {
            while ((n = bis.read()) != -1) {    //一个字节一个字节的读取，并将读取字节的ASCII存入n中
                bos.write(n);
            }
        } catch (Exception e) {
            System.out.println("输入流 读取/写入 异常");
            e.printStackTrace();
        } finally {
            bos.close();    //关闭输出流、输入流
            bis.close();
        }
        System.out.println(saveFileRealPath);
        return newFileName;
    }
}
